#include "rtspserver.h"
#include "rtspsession.h"
#include <QTcpSocket>

RtspServer::RtspServer(QObject *parent) : QTcpServer(parent)
{

}

bool RtspServer::start(quint16 port)
{
    return listen(QHostAddress::Any, port);
}

void RtspServer::incomingConnection(qintptr socketDescriptor)
{
    QTcpSocket *socket = new QTcpSocket(this);
    if (!socket->setSocketDescriptor(socketDescriptor))
    {
        delete socket;
        return;
    }

    RtspSession *session = new RtspSession(socket, this);
    m_clients.insert(socket, session);

    connect(socket, &QTcpSocket::disconnected,
            this, &RtspServer::onClientDisconnected);
}

void RtspServer::onClientDisconnected()
{
    QTcpSocket *socket = qobject_cast<QTcpSocket*>(sender());
    if (socket && m_clients.contains(socket))
    {
        delete m_clients.take(socket);
        socket->deleteLater();
    }
}
